package helloWorld.musicplayer;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;

public class Scraper {

	protected int curPos; // global cursorPosition
	protected boolean mustFindEnd;
	protected String capturedData; // capturedMp3Id --> global temp

	protected String url;
	protected String startPattern;
	protected char endPattern;

	protected String offsetString;
	protected int maxToFind;

	private boolean initialized;

	public void setMaxToFind(int maxToFind) {
		this.maxToFind = maxToFind;
	}

	protected Vector<String> capturedList; // list of captured items

	public Scraper() {
		capturedList = new Vector<String>();
		maxToFind = 1;
		url = "";
		startPattern = "";
		endPattern = ' ';
		offsetString = "";
		initialized = false;
	}

	public Vector<String> getResultList() // getmp3list
	{
		return capturedList;
	}

	protected boolean searchForPattern(String temp) {
		boolean result = false;

		for (int i = 0; i < temp.length(); ++i) {
			if (temp.charAt(i) == offsetString.charAt(curPos)) {
				curPos++;
				if (curPos >= offsetString.length()) {
					curPos = 0;
					result = true;
				}
			} else {
				curPos = 0;
			}
		}
		return result;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getStartPattern() {
		return startPattern;
	}

	public void setStartPattern(String startPattern) {
		this.startPattern = startPattern;
	}

	public char getEndPattern() {
		return endPattern;
	}

	public void setEndPattern(char endPattern) {
		this.endPattern = endPattern;
	}

	public String getOffsetString() {
		return offsetString;
	}

	public void setOffsetString(String offsetString) {
		this.offsetString = offsetString;
	}

	protected boolean captureData(String temp) {
		boolean result = false;

		for (int i = 0; i < temp.length(); ++i) {
			if (!mustFindEnd) {
				if (temp.charAt(i) == startPattern.charAt(curPos)) {
					curPos++;
					if (curPos >= startPattern.length()) {
						mustFindEnd = true;
						curPos = 0;
					}
				} else {
					curPos = 0;
				}
			} else {
				boolean captureLetter = false;

				if (temp.charAt(i) == endPattern) {
					mustFindEnd = false;
					result = true;
					captureLetter = false;

					if (capturedList.size() < maxToFind){
						capturedData = capturedData.substring(0, capturedData.length()-1);
						capturedList.add(capturedData);
					}

					// AlertDialog.Builder buildy = new
					// AlertDialog.Builder(context);
					// buildy.setMessage(capturedData);
					// buildy.show();

					capturedData = "";
				} else {
					captureLetter = true;
				}

				if (captureLetter)
					capturedData += temp.charAt(i);
			}

		}
		return result;
	}

	protected InputStream OpenHttpConnection(String urlString)
			throws IOException {
		System.setProperty("http.keepAlive", "false");
		InputStream in = null;
		int response = -1;

		URL urlConn = new URL(urlString);
		URLConnection conn = urlConn.openConnection();

		if (!(conn instanceof HttpURLConnection))
			throw new IOException("Not an HTTP connection");

		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();

			response = httpConn.getResponseCode();
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();
			} else {
				in = null;
			}
		} catch (Exception ex) {

			throw new IOException("Error connecting");
		}
		return in;
	}

	protected boolean initialize(String url, String startPattern,
			char endPattern, String offsetString, int maxToFind) {

		this.url = url;
		this.startPattern = startPattern;
		this.endPattern = endPattern;
		this.offsetString = offsetString;
		this.maxToFind = maxToFind;

		initialized = true;
		return true;
	}

	protected boolean searchForData() {
		if (!initialized)
			return false;

		boolean songsFound = false;
		int BUFFER_SIZE = 20000;
		InputStream in = null;

		try {
			in = OpenHttpConnection(url);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			return false;
		}

		if (in == null)
			return false;

		InputStreamReader isr = new InputStreamReader(in);
		int charRead;
		char[] inputBuffer = new char[BUFFER_SIZE];

		mustFindEnd = false;
		capturedData = "";
		try {
			// first look for tracklist
			curPos = 0;
			boolean targetFound = false;
			boolean lookForMp3s = false;

			while (!targetFound && (charRead = isr.read(inputBuffer)) > -1) {

				// ---convert the chars to a String---
				String readString = String
						.copyValueOf(inputBuffer, 0, charRead);

				// watch out!, its possible there are already tracks in our
				// buffer!
				targetFound = searchForPattern(readString);
				if (targetFound) {

					lookForMp3s = captureData(readString);
					songsFound = lookForMp3s;
				}
				inputBuffer = new char[BUFFER_SIZE];
			}

			// now look for mp3s
			curPos = 0;
			capturedData = "";
			targetFound = false;
			if (lookForMp3s) {

				while (capturedList.size() < maxToFind
						&& (charRead = isr.read(inputBuffer)) > 0) {

					// ---convert the chars to a String---
					String readString = String.copyValueOf(inputBuffer, 0,
							charRead);
					// str += readString + "\n";
					targetFound = captureData(readString);
					if (targetFound) {
						capturedData = "";
						targetFound = false;
					}
					inputBuffer = new char[BUFFER_SIZE];
				}
			}

			in.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			return false;
		}

		return songsFound;
	}
}
